package com.jiubanqingchen.interceptors;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.jiubanqingchen.framework.base.controller.BaseController;
import com.jiubanqingchen.framework.context.locale.LocaleContextHolder;
import com.jiubanqingchen.framework.enums.SystemStatus;
import com.jiubanqingchen.kit.ApplicationKit;
import com.jiubanqingchen.kit.ExceptionKit;
import com.jiubanqingchen.kit.I18nKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * @author light_dust
 * @since 2020/12/28 17:25
 */
public class GlobalInterceptor implements Interceptor {
    private final Logger logger = LoggerFactory.getLogger(GlobalInterceptor.class);

    @Override
    public void intercept(Invocation inv) {
        BaseController controller = (BaseController) inv.getController();
        try {
            //判断是否开启国际化 开启则保存至本地
            if (ApplicationKit.me().getI18nEnable()) {
                //获取当前session中的语言
                HttpServletRequest request = controller.getRequest();
                String locale = request.getHeader("locale");// 得到当前token
                if (StrKit.notBlank(locale)) LocaleContextHolder.setLocale(I18nKit.getLocaleFromString(locale));
            }
            inv.invoke();
        } catch (RuntimeException wishException) {
            controller.renderJson(SystemStatus.ERROR, wishException.getMessage(), ExceptionKit.getStackTrace(wishException));
            wishException.printStackTrace();
        }
    }


}
